/*
 * Copyright 2008-2009 Aying.Net Powered by Fuchun.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.aying.media.audio;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import net.aying.util.FileUtils;
import net.aying.util.IOUtils;
import net.aying.util.JSONUtils;
import net.aying.util.NumberUtils;
import net.aying.util.StringUtils;


/**
 * {@code AudioFactory} 音频抽象工厂的默认实例。
 * 
 * @author  Fuchun
 * @version 1.0, 2009-07-21
 */
public class AudioFactoryImpl extends AudioFactory {
    
    private byte[] audioFileBytes = null;

    /**
     * @see net.aying.media.audio.AudioFactory#createAudio(java.lang.String)
     */
    public Audio createAudio(String audioPath) throws UnsupportedAudioException, IOException {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see net.aying.media.audio.AudioFactory#createAudio(java.io.File)
     */
    public Audio createAudio(File audioFile) throws UnsupportedAudioException, IOException {
        return initAudioFileBytes(audioFile);
    }

    /**
     * @see net.aying.media.audio.AudioFactory#createAudio(java.net.URL)
     */
    public Audio createAudio(URL audioURL) throws UnsupportedAudioException, IOException {
        // TODO Auto-generated method stub
        return null;
    }
    
    // 初始化音频文件字节数组
    private Audio initAudioFileBytes(File file) throws UnsupportedAudioException, IOException {
        byte[] audioBytes = getMP3Info(file);
        if(audioBytes != null) {
            String mp3Tag = new String(audioBytes, 0, AudioMP3.MP3_TAG.length());
            // 确定该文件是 mp3
            if(AudioMP3.MP3_TAG.equalsIgnoreCase(mp3Tag)) {
                return parseMP3Info(audioBytes);
            }
        }
        throw new UnsupportedAudioException("Unsupported audio");
    }
    
    private byte[] getMP3Info(File mp3) {
        if (mp3 == null || !mp3.exists() || mp3.isDirectory()
                || mp3.length() <= AudioMP3.TAG_SIZE) {
            return null;
        }
        try {
            RandomAccessFile raf = new RandomAccessFile(mp3, "r");
            raf.seek(raf.length() - AudioMP3.TAG_SIZE);
            byte[] bytes = new byte[AudioMP3.TAG_SIZE];
            raf.read(bytes, 0, AudioMP3.TAG_SIZE);
            return bytes;
        } catch (Exception ex) {
            return null;
        }
    }
    
    private Audio parseMP3Info(byte[] mp3Bytes) throws UnsupportedEncodingException {
        AudioMP3 mp3 = new AudioMP3();
        String mp3Info = new String(mp3Bytes, 0, AudioMP3.TAG_SIZE, AudioMP3.MP3_ENCODING);
        int start = AudioMP3.MP3_TAG.length();
        String title = mp3Info.substring(start, start += AudioMP3.TITLE_LEN).trim();
        String artist = mp3Info.substring(start, start += AudioMP3.ARTIST_LEN).trim();
        String album = mp3Info.substring(start, start += AudioMP3.ALBUM_LEN).trim();
        title = StringUtils.transcoding(title, AudioMP3.MP3_ENCODING, "GBK");
        artist = StringUtils.transcoding(artist, AudioMP3.MP3_ENCODING, "GBK");
        album = StringUtils.transcoding(album, AudioMP3.MP3_ENCODING, "GBK");
        Integer track = NumberUtils.parseInt(String.valueOf(mp3Info.charAt(AudioMP3.TRACK_LOCATION)));
        mp3.setTitle(title);
        mp3.setArtist(artist);
        mp3.setAlbum(album);
        mp3.setTrack(track);
        return mp3;
    }
    
    public static void main(String[] args) throws Exception {
        AudioFactory factory = AudioFactory.newInstance();
        Audio mp3 = factory.createAudio(new File("G:\\我的音乐\\许巍\\许巍 - 彩虹.mp3"));
        System.out.println(JSONUtils.toJson(mp3, false));
    }
}
